/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.epidemy.jmdns

import scala.actors._
import scala.actors.remote._
import javax.jmdns._
import scala.collection.JavaConversions._

import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.codec.binary.{Hex, Base64}
      

case class DNSActor(jmdns: JmDNS, key: String, resolved: ServiceInfo => Unit, unresolved: ServiceInfo => Unit) extends Actor with ServiceListener {
  case class ServiceAdded(event: ServiceEvent)
  case class ServiceResolved(event: ServiceEvent)
  case class ServiceRemoved(event: ServiceEvent)

  override def start: DNSActor = {
    super.start
    jmdns.addServiceListener(key, this)
    discover
    this
  }
  def discover = jmdns.requestServiceInfo(key, null)
  
  def act: Unit = {
    loop {
      react {
        case ServiceAdded(event) => {
            //println("ADDED:\n\t" + event + "\n\tinfo = " + event.getInfo)
            val info = event.getInfo
            val m = info.getPropertyNames.map(n => (n, info.getPropertyString(n)))
            if (info != null && !m.isEmpty)//info.getPropertyString("port") != null)
              resolved(info)
            else
              new Thread { override def run: Unit = event.getDNS.requestServiceInfo(event.getType, event.getName) }.start
          }
        case ServiceResolved(event) => 
          //println("RESOLVED:\n\t" + event + "\n\tinfo = " + event.getInfo)
          resolved(event.getInfo)
        case ServiceRemoved(event) => unresolved(event.getInfo)
      }
    }
  }
  override def serviceAdded(evt: ServiceEvent) = this ! new ServiceAdded(evt)
  override def serviceResolved(evt: ServiceEvent) = this ! new ServiceResolved(evt)
  override def serviceRemoved(evt: ServiceEvent) = this ! new ServiceRemoved(evt)
}